package demo;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JTextPane;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.undo.UndoManager;

public class UndoFunction extends JFrame{

    /**
     * @param args
     * 实现简单的撤销功能，并通过Ctrl+Z快捷键来快速操作,这次是在一个文本面板中，既可以写文字又可以插入图片，可以撤销也可以恢复
     * 通过鼠标右键来弹出菜单实现撤销和恢复的操作
     */
    private UndoManager um;//撤销管理类
    private JTextPane jp;//文本面板
    private String name[]={
            "撤销",
            "恢复",
            "插入图片"
    };
    private JPopupMenu pm;//右键弹出菜单类
    private JMenuItem mt[];
    public UndoFunction(){
        um=new UndoManager();
        jp=new JTextPane();
        pm=new JPopupMenu();
        mt=new JMenuItem[3];
        for(int i=0;i<3;++i){
            mt[i]=new JMenuItem(name[i]);
            pm.add(mt[i]);
            mt[i].addActionListener(new PopupAction());
        }
        add(jp);
        jp.addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                maybeShowPopup(e);
            }
            public void mouseReleased(MouseEvent e){
                maybeShowPopup(e);
            }
            private void maybeShowPopup(MouseEvent e){
                if(e.isPopupTrigger()){//如果有弹出菜单
                    pm.show(e.getComponent(), e.getX(), e.getY());
                }
            }
        });
        jp.getDocument().addUndoableEditListener(new UndoableEditListener(){//注册撤销可编辑监听器
            public void undoableEditHappened(UndoableEditEvent e) {
                um.addEdit(e.getEdit());
            }

        });//编辑撤销的监听
    }
    public static void main(String[] args) {
//        SwingConsole.swingRun(new UndoFunction(),600,400);
        UndoFunction d = new UndoFunction();
        d.setLocation(600, 400);
        d.setVisible(true);
    }
    class PopupAction implements ActionListener{
        public void actionPerformed(ActionEvent e) {
            if(e.getSource()==mt[0]&&um.canUndo()){//撤销
                um.undo();
            }else if(e.getSource()==mt[1]&&um.canRedo()){//恢复
                um.redo();
            }else if(e.getSource()==mt[2]){//插入图片
                System.out.println(getClass());
                System.out.println(getClass().getResource("1.png"));
                ImageIcon icon=new ImageIcon(getClass().getResource("1.png"));
                jp.insertIcon(icon);
            }
        }
    }
}
